package com.kuangstudy.caffeine.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.kuangstudy.caffeine.domain.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年10月09日
 * @Description
 */
@RestController
@Slf4j
@Api(tags = "测试Caffeine")
public class TestController {

    @Autowired
    private Cache<String, Object> caffeineCache;

    @GetMapping("/test/cache/{userId}")
    @ApiOperation("本地缓存用户信息")
    public UserInfo testCache(@PathVariable("userId") Integer userId) {
        UserInfo userInfoCache = (UserInfo) caffeineCache.asMap().get("user:caffeine:" + userId);
        if (Objects.nonNull(userInfoCache)) {
            return userInfoCache;
        }
        // todo 模拟查询数据库查询出的user对象
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1);
        userInfo.setName("占山");
        userInfo.setAge(18);
        userInfo.setSex("man");
        if (Objects.nonNull(userInfo)) {
            caffeineCache.put("user:caffeine:" + userId, userInfo);
        }
        return userInfo;
    }

}
